package top.chukongxiang.project.base.oauth2.provider.cas;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.cas.authentication.CasAssertionAuthenticationToken;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import top.chukongxiang.project.base.model.entity.sys.Role;
import top.chukongxiang.project.base.model.entity.user.RoleUser;
import top.chukongxiang.project.base.model.entity.user.User;
import top.chukongxiang.project.base.oauth2.UserInfo;
import top.chukongxiang.project.base.service.sys.RoleService;
import top.chukongxiang.project.base.service.user.RoleUserService;
import top.chukongxiang.project.base.service.user.UserService;
import top.chukongxiang.project.base.utils.FastJsonUtil;

import java.util.Map;

/**
 * @author 楚孔响
 * @version 1.0
 * @date 2021/12/31 16:45
 */
@Component
public class CasAuthenticationUserDetailsServiceImpl implements AuthenticationUserDetailsService<CasAssertionAuthenticationToken> {

    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    @Autowired
    RoleUserService roleUserService;

    @Override
    public UserDetails loadUserDetails(CasAssertionAuthenticationToken token) throws UsernameNotFoundException {
        Map<String, Object> userAttributes = token.getAssertion().getPrincipal().getAttributes();
        String staffId = (String) userAttributes.get("staffNo");
        if (staffId == null) {
            throw new UsernameNotFoundException("无法获取员工号");
        }

        User user = FastJsonUtil.bean2Bean(userAttributes, User.class);

        boolean success;

        if(userService.existsById(user.getId())) {
            success = userService.updateById(user);
        } else {
            // 获取默认角色
            Role role = roleService.defaultRole();
            if (role == null) {
                throw new UsernameNotFoundException("无法分配您的角色，请联系管理员");
            }
            success = userService.save(user);
            if (success) {
                roleUserService.save(new RoleUser(null, role.getId(), user.getId()));
            }
        }

        if (!success) {
            throw new UsernameNotFoundException("当前用户无权限，请联系管理员");
        }

        return new UserInfo(user.getStaffNo(), user.getStaffNo(), user.getId());
    }
}
